VendorSearch = LibStub("AceAddon-3.0"):NewAddon("VendorSearch", "AceConsole-3.0", "AceEvent-3.0")


--------------------
--Defaults Params:--
--------------------
KeywordType="name"
VendorSearch.OpacityHiding = true
VendorSearch.FullHiding = false
VendorSearch.HidePriceFilter = false
VendorSearch.HideNonUsable = false
VendorSearch.Slider1 = 0.15
VendorSearch.Slider2 = 0.5
VendorSearch.Version = 1.95
VendorSearch.Verbose = false


local options = {
    name = "VendorSearch",
    handler = VendorSearch,
    type = "group",
    args = {

 	    about = {
		     type = "group",
		     name = "About",
		     order = 2,
		     args = {
		     		about = {
		     			type = "description",
		     			name = "Version " .. VendorSearch.Version .. "\n\n Made by Adriweb, 2009.  \n\n Please Donate if you enjoy it :D",
		 			},
		 	},
		},
 	    help = {
		     type = "group",
		     name = "Help",
		     order = 1,
		     args = {
		     		help = {
		     			type = "description",
		     			name = "By default, the addon is set with these settings : \n     Graphical Mode \n     Opacity Hiding Mode \n     Type of search : by Name \n     Other filters disabled (non-usable / too expensive items) \n\nYou can change these settings either in the Options Tab, or directly into the Vendor's frame (for the search type, for example). \n After that, just type in your keywords (or the numbers, depending on your search type) in the second text box. \n\n\nThe differents parameters for the search type are : \n    name\n    price < (in copper)\n    price > (in copper)\n    rarity (number from 1 to 6, poor to artifact)\n    type (ex: armor)\n    subtype (ex: cloth)",
		 			},
		 	},
		},
		Options = {
	     	type = "group",
	     	name = "Options",
    	 	desc = "Configure VendorSearch",
    	 	order = 0,
			args = {
     			Verbose = {
	     			type = "toggle",
	     			name = "Debug/Textual mode",
    	 			desc = "Toggle the Debug/Textual mode",
					set = "ToggleVerbose",
					get = "IsVerbose",
					order = 6,
     			},
     			OpacityHiding = {
	     			type = "toggle",
	     			name = "Opacity Hiding mode",
    	 			desc = "Toggle the hiding mode to opacity mode",
					set = "ToggleOpacityHiding",
					get = "IsOpacityHiding",
					order = 1,
     			},
     			FullHiding = {
	     			type = "toggle",
	     			name = "Full Hiding mode",
    	 			desc = "Toggle the hiding mode to Full Hiding mode",
					set = "ToggleFullHiding",
					get = "IsFullHiding",
					order = 0,
     			},
     			HideNonUsable = {
	     			type = "toggle",
	     			name = "Hide nonusable items",
    	 			desc = "Automatically hides the items you can't wear/use",
					set = "ToggleHideNonUsable",
					get = "IsHideNonUsable",
					order = 2,
				},
				HideNonBuyable = {
	     			type = "toggle",
	     			name = "Hide nonbuyable items",
    	 			desc = "Automatically hides the items you can't afford.",
					set = "ToggleHidePriceFilter",
					get = "IsHidePriceFilter",
					order = 3,
				},
				Slider1 = {
					name = "Non-Result Alpha Slider",
					desc = "Set the Alpha for Hiding the non-results items.",
	     			type = "range",
	     			min = 0,
	     			max = 1,
	     			step = 0.05,
					set = "SetSlider1",
					get = "GetSlider1",
					order = 4,
				},
				Slider2 = {
					name = "Filter Alpha Slider",
					desc = "Set the Alpha for Hiding the filtered items.",
	     			type = "range",
	     			min = 0,
	     			max = 1,
	     			step = 0.05,
					set = "SetSlider2",
					get = "GetSlider2",
					order = 5,
				},
				
     		},
     	},
	},
}



function VendorSearch:OnInitialize()
	LibStub("AceConfig-3.0"):RegisterOptionsTable("VendorSearch", options)
    self.optionsFrame = LibStub("AceConfigDialog-3.0"):AddToBlizOptions("VendorSearch", "VendorSearch")
    self:RegisterChatCommand("vendorsearch", "ChatCommand")
 	self:RegisterChatCommand("vs", "ChatCommand")
end

function VendorSearch:OnEnable()
    -- Called when the addon is enabled
    DEFAULT_CHAT_FRAME:AddMessage("VendorSearch " .. VendorSearch.Version .. " : Loaded")
    self:RegisterEvent("MERCHANT_SHOW")
end


function VendorSearch:OnDisable()
    -- Called when the addon is disabled
end


totalitems = GetMerchantNumItems();
money = GetMoney();


--------------
--SearchBox:--
--------------

local searchbox = CreateFrame("EditBox","MerchantFrameSearchFrame",MerchantFrame,"InputBoxTemplate")
searchbox:SetFrameStrata("HIGH")
searchbox:SetAutoFocus(nil)
searchbox:SetWidth(158)
searchbox:SetHeight(26)
searchbox:SetPoint("TOP",49,-45)
searchbox:SetText("Enter keyword here")
searchbox:SetScript("OnEnterPressed", function(self)
	Keyword = searchbox:GetText()
	searchbox:ClearFocus()
	VendorSearch:Search(Keyword)
end)
searchbox:SetScript("OnTextChanged", function(self)
Keyword = searchbox:GetText()
VendorSearch:Search(Keyword)
end)
searchbox:SetScript("OnMouseDown", function(self)
 if searchbox:GetText() == "Enter keyword here" then
	searchbox:SetText("")
 end
end)

local searchboxtype = CreateFrame("Frame", "MerchantFrameSearchTypeFrame", MerchantFrame, "UIDropDownMenuTemplate");
searchboxtype:SetFrameStrata("HIGH")
UIDropDownMenu_SetWidth(searchboxtype, 70)
searchboxtype:SetHeight(26)
searchboxtype:SetPoint("TOP",-73,-45)

local function VsUpdate(self)
	UIDropDownMenu_SetSelectedValue(searchboxtype, self.value)
	KeywordType = self.value
	searchboxtype.value = self.value
	searchbox:SetFocus()
end

local function VsSearchDropDownInit(level)
	local info = UIDropDownMenu_CreateInfo()
	
	local info = {
		text = "物品名",
		value = "name",
		func = VsUpdate,
	}
	if KeywordType == info.value then
		info.checked = 1;
		UIDropDownMenu_SetText(searchboxtype, info.text);
	else
		info.checked = nil;
	end
	UIDropDownMenu_AddButton(info)
	
	--type
	local info = {
		text = "类别",
		value = "type",
		func = VsUpdate,
	}
	if KeywordType == info.value then
		info.checked = 1;
		UIDropDownMenu_SetText(searchboxtype, info.text);
	else
		info.checked = nil;
	end
	UIDropDownMenu_AddButton(info)

	--子类别subtype
	local info = {
		text = "子类别",
		value = "subtype",
		func = VsUpdate,
	}
	if KeywordType == info.value then
		info.checked = 1;
		UIDropDownMenu_SetText(searchboxtype, info.text);
	else
		info.checked = nil;
	end
	UIDropDownMenu_AddButton(info)

	--rarity
	local info = {
		text = "稀有等级",
		value = "rarity",
		func = VsUpdate,
	}
	if KeywordType == info.value then
		info.checked = 1;
		UIDropDownMenu_SetText(searchboxtype, info.text);
	else
		info.checked = nil;
	end
	UIDropDownMenu_AddButton(info)

	--价格price price >
	local info = {
		text = "价格 >",
		value = "price >",
		func = VsUpdate,
	}
	if KeywordType == info.value then
		info.checked = 1;
		UIDropDownMenu_SetText(searchboxtype, info.text);
	else
		info.checked = nil;
	end
	UIDropDownMenu_AddButton(info)

	--价格price price <
	local info = {
		text = "价格 <",
		value = "price <",
		func = VsUpdate,
	}
	if KeywordType == info.value then
		info.checked = 1;
		UIDropDownMenu_SetText(searchboxtype, info.text);
	else
		info.checked = nil;
	end
	UIDropDownMenu_AddButton(info)
end
UIDropDownMenu_Initialize(searchboxtype, VsSearchDropDownInit)

local RefreshButton = CreateFrame("Button","MerchantFrameRefreshButton",MerchantFrame)
RefreshButton:SetFrameStrata("HIGH")
RefreshButton:SetNormalTexture("Interface\\Buttons\\UI-RotationLeft-Button-Up")
RefreshButton:SetPushedTexture("Interface\\Buttons\\UI-RotationLeft-Button-Down")
RefreshButton:SetHighlightTexture("Interface\\Buttons\\UI-RotationLeft-Button-Up")
RefreshButton:SetWidth(29)
RefreshButton:SetHeight(27)
RefreshButton:SetPoint("TOP",137,-45)
RefreshButton:RegisterForClicks("AnyUp");
RefreshButton:SetScript("OnClick", function(self)
	Keyword = searchbox:GetText()
	VendorSearch:Search(Keyword)
end)
	

--------------
--Functions:--
--------------

function VendorSearch.SetKeywordType(type)
	KeywordType = type
end

function update()
    NewCurrPage = MerchantFrame.page
    TotalPages = math.ceil(GetMerchantNumItems() / MERCHANT_ITEMS_PER_PAGE)
    if KeywordType == "name" then
 		--searchboxtype:SetValue("name")
 	end
	if CurrPage and not (NewCurrPage == CurrPage) then
			KeywordType = searchboxtype.value
			Keyword = searchbox:GetText()
			if Keyword and not (Keyword == "Enter keyword here") then
				VendorSearch:Search(Keyword)
			end
	end
end
hooksecurefunc("MerchantFrame_Update", update);


function VendorSearch:IsVerbose(info)
    return VendorSearch.Verbose
end

function VendorSearch:ToggleVerbose(info, value)
    VendorSearch.Verbose = value
    VendorSearch:Search(Keyword)
end

function VendorSearch:IsOpacityHiding(info)
    return VendorSearch.OpacityHiding
end

function VendorSearch:ToggleOpacityHiding(info, value)
    VendorSearch.OpacityHiding = value
    VendorSearch.FullHiding = not value
    VendorSearch:Search(Keyword)
end

function VendorSearch:IsFullHiding(info)
    return VendorSearch.FullHiding
end

function VendorSearch:ToggleFullHiding(info, value)
    VendorSearch.FullHiding = value
    VendorSearch.OpacityHiding = not value
    VendorSearch:Search(Keyword)
end

function VendorSearch:IsHidePriceFilter(info)
    return VendorSearch.HidePriceFilter
end

function VendorSearch:ToggleHidePriceFilter(info, value)
    VendorSearch.HidePriceFilter = value
    VendorSearch:Search(Keyword)
end

function VendorSearch:IsHideNonUsable(info)
    return VendorSearch.HideNonUsable
end

function VendorSearch:ToggleHideNonUsable(info, value)
    VendorSearch.HideNonUsable = value
    VendorSearch:Search(Keyword)
end

function VendorSearch:GetSlider1(info)
    return VendorSearch.Slider1
end

function VendorSearch:SetSlider1(info, value)
    VendorSearch.Slider1 = value
    VendorSearch:Search(Keyword)
end

function VendorSearch:GetSlider2(info)
    return VendorSearch.Slider2
end

function VendorSearch:SetSlider2(info, value)
    VendorSearch.Slider2 = value
    VendorSearch:Search(Keyword)
end


function VendorSearch:MERCHANT_SHOW()
 VendorSearch:MERCHANT_LIST()
	for i=1,totalitems do
		name, texture, price, quantity, numAvailable, isUsable, extendedCost = GetMerchantItemInfo(i);
		link = GetMerchantItemLink(i);
		VendorSearch.itemname = name
		VendorSearch.Items = getglobal("MerchantItem" .. i)
		if newitemid then
			if (newitemid <= 10) and (10 <= totalitems) then
				VendorSearch:Filter();
			end
		end
		if VendorSearch.Verbose == true then
 			DEFAULT_CHAT_FRAME:AddMessage("Item " .. i .. " : " .. link .. " - " .. price .. " copper");
		end
 	end
	if Keyword and not (Keyword == "Enter keyword here") then
		VendorSearch:Search(Keyword)
	end
end


function VendorSearch:Filter()
		if VendorSearch.HidePriceFilter == true then
			if price > money then
				VendorSearch.Items:SetAlpha(VendorSearch.Slider2);
			end
		end
		if VendorSearch.HideNonUsable == true then
			if not isUsable then
				VendorSearch.Items:SetAlpha(VendorSearch.Slider2);
			end
		end
end



function VendorSearch:Search(Keyword)

UIErrorsFrame:UnregisterEvent("UI_ERROR_MESSAGE");
VendorSearch.found = 0
links = ""

CurrPage = MerchantFrame.page
if VendorSearch.Verbose == true then
DEFAULT_CHAT_FRAME:AddMessage("CurrPage= " .. CurrPage)
end

searchstart=((10 * CurrPage) - 10 + 1)
i=1

 while GetMerchantItemInfo(i) and i <= searchstart + 9 do

 	CurrPage = MerchantFrame.page

 	name, texture, price, quantity, numAvailable, isUsable, extendedCost = GetMerchantItemInfo(i);
	   link = GetMerchantItemLink(i);
 	   VendorSearch.itemname = name
 	   VendorSearch.itemprice = price
	sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount = GetItemInfo(link);
 	   ipart = math.floor((i / 10))
 	   if (i / 10) == ipart then
 	   itempage = ipart
 	   newitemid = i - (10 * ipart) + 1
 	   	if i == 10 then
 	   	newitemid = 10
 	   	end
 	   else
 	   itempage = 1 + ipart
 	   newitemid = i - (10 * ipart)
 	   end
 	VendorSearch.Items = getglobal("MerchantItem" .. newitemid)
 if Keyword and not (Keyword == "Enter keyword here") then
 	if KeywordType == "name" and string.find(strlower(VendorSearch.itemname), strlower(Keyword)) then
			if VendorSearch.Verbose == true then
			DEFAULT_CHAT_FRAME:AddMessage(VendorSearch.itemname .. " is a result")
			end
 		VendorSearch:montrer();
 		VendorSearch:Filter();
  				VendorSearch.found = VendorSearch.found + 1
 				if links == "" then
 					links = links .. link .. " - " .. price .. "c"
 				else
 					links = links .. " , \n" .. link .. " - " .. price .. "c"
 				end
 				if i == totalitems then
					if VendorSearch.Verbose == true then
						DEFAULT_CHAT_FRAME:AddMessage(" ")
						DEFAULT_CHAT_FRAME:AddMessage("Results of search : Item(s) found from keyword \"" .. Keyword .. "\" : " .. VendorSearch.found)
						DEFAULT_CHAT_FRAME:AddMessage(links)
						DEFAULT_CHAT_FRAME:AddMessage(" ")
					end
				end
				
	elseif KeywordType == "price <" and Keyword and tonumber(VendorSearch.itemprice) <= tonumber(Keyword) then	
			if VendorSearch.Verbose == true then
			DEFAULT_CHAT_FRAME:AddMessage(VendorSearch.itemname .. " is a result")
			end
 		VendorSearch:montrer();
 		VendorSearch:Filter();
	
	elseif KeywordType == "price >" and tonumber(VendorSearch.itemprice) >= tonumber(Keyword) then	
			if VendorSearch.Verbose == true then
				DEFAULT_CHAT_FRAME:AddMessage(VendorSearch.itemname .. " is a result")
			end
 		VendorSearch:montrer();
 		VendorSearch:Filter();
 		
	elseif KeywordType == "rarity" and iRarity and tonumber(iRarity) >= tonumber(Keyword) then	
			if VendorSearch.Verbose == true then
			DEFAULT_CHAT_FRAME:AddMessage(VendorSearch.itemname .. " is a result")
			end
 		VendorSearch:montrer();
 		VendorSearch:Filter();
 		
 	elseif KeywordType == "type" and string.find(strlower(sType), strlower(Keyword)) then	
			if VendorSearch.Verbose == true then
			DEFAULT_CHAT_FRAME:AddMessage(VendorSearch.itemname .. " is a result")
			end
 		VendorSearch:montrer();
 		VendorSearch:Filter();
 		
 	elseif KeywordType == "subtype" and string.find(strlower(sSubType), strlower(Keyword)) then	
			if VendorSearch.Verbose == true then
			DEFAULT_CHAT_FRAME:AddMessage(VendorSearch.itemname .. " is a result")
			end
 		VendorSearch:montrer();
 		VendorSearch:Filter();
	
 	else
 		VendorSearch:cacher();
	end
 end -- if keyword
i=(i + 1)
end --for
UIErrorsFrame:RegisterEvent("UI_ERROR_MESSAGE");
end --function


function VendorSearch:cacher()
	if VendorSearch.FullHiding == true then
	    VendorSearch.Items:Hide();
	else
		VendorSearch.Items:SetAlpha(VendorSearch.Slider1);
	end
end

function VendorSearch:montrer()
	VendorSearch.Items:Show();
	VendorSearch.Items:SetAlpha(1);
end

function VendorSearch:MERCHANT_LIST()
totalitems = GetMerchantNumItems();
	if VendorSearch.Verbose == true then
		DEFAULT_CHAT_FRAME:AddMessage("Number of items : " .. totalitems);
	end
end


--------------
--Ace Stuff:--
--------------

function VendorSearch:ChatCommand(input)
   if (not input or input:trim() == "") then
        --InterfaceOptionsFrame_OpenToFrame(self.optionsFrame)
        LibStub("AceConfigDialog-3.0"):Open("VendorSearch")
    else
        LibStub("AceConfigCmd-3.0").HandleCommand(VendorSearch, "vs", "VendorSearch", input)
    end
end

function VendorSearch:ShowOptions()
    LibStub("AceConfigDialog-3.0"):Open("VendorSearch")
end